// Canvas.java
// by Alexandre Martins, 2013
// MAC 5857 - Prof. Leonidas

package example.ilm.gui;

import example.ilm.model.GeometricElement;
import example.ilm.model.Polygon;
import example.ilm.model.Workspace;

import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Observer;
import java.util.Observable;

import java.awt.Graphics2D;
import java.awt.Color;

public class Canvas implements Observer
{
    private List renderers;
    private GeometricElement focusedObject;

    public Canvas()
    {
        renderers = new ArrayList();
        focusedObject = null;
    }

    public void render(Graphics2D g)
    {
        GeometricElementRenderer f = null;

        Iterator it = renderers.iterator();
        while(it.hasNext()) {
            GeometricElementRenderer r = (GeometricElementRenderer)(it.next());
            if(focusedObject != null && r.getGeometricElement().equals(focusedObject)) {
                f = r;
                if(!f.getGeometricElement().isBeingDragged())
                	f.render(g);
            }
            else
                r.render(g);
        }

        if(f != null) {
        	if(f.getGeometricElement().isBeingDragged())
        		f.renderTranslucent(g);
            f.renderVertices(g);
        }
    }

    public void update(Observable o, Object arg)
    {
        // recebi atualizacao do Workspace
        Workspace wksp = (Workspace)o;

        if(arg instanceof List)
            renderers = rebuildRenderers((List)arg);
        else
            focusedObject = (GeometricElement)arg;
    }




    private List rebuildRenderers(List geometricElements)
    {
        List renderers = new ArrayList();

        Iterator it = geometricElements.iterator();
        while(it.hasNext()) {
            Object o = it.next();
            if(o instanceof Polygon) // q feio :(
                renderers.add( new PolygonRenderer((Polygon)o) );
        }

        return renderers;
    }
}
